package com.daffodil.storage.config;

import com.daffodil.storage.properties.MinioProperties;
import com.daffodil.storage.properties.StorageProperties;

import cn.hutool.core.util.ObjectUtil;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * 
 * @author yweijian
 * @date 2022年12月8日
 * @version 2.0.0
 * @description
 */
@Slf4j
@Component
@Configuration
@ConditionalOnProperty(name = StorageProperties.NAME, havingValue = StorageProperties.MINIO)
public class MinioClientConfig {

    @Bean
    @ConditionalOnMissingBean
    public MinioClient minioClient(StorageProperties storageProperties) throws MinioException {
        MinioProperties properties = storageProperties.getMinio();
        String endpoint = properties.getEndpoint();
        String accessKey = properties.getAccessKey();
        String secretKey = properties.getSecretKey();
        String bucketName = properties.getBucketName();
        if(ObjectUtil.isEmpty(endpoint)) {
            throw new MinioException("Minio-Endpoint未配置");
        }
        if(ObjectUtil.isEmpty(accessKey)) {
            throw new MinioException("Minio-AccessKey未配置");
        }
        if(ObjectUtil.isEmpty(secretKey)) {
            throw new MinioException("Minio-AecretKey密码未配置");
        }
        if(ObjectUtil.isEmpty(bucketName)) {
            throw new MinioException("Minio-BucketName未配置");
        }
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
        this.makeBucket(minioClient, bucketName);
        return minioClient;
    }

    private void makeBucket(MinioClient minioClient, String bucketName) throws MinioException {
        try {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                String policyJson = "Bucket already exists.";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new MinioException("创建Minio对象存储桶异常");
        }
    }

}
